const express = require(`express`)
const fetch = require('node-fetch')
const router = express.Router()

const GITEE_API = "https://gitee.com/api/v5";

const access_token = process.env.VUE_APP_ACCESS_TOKEN;
const repo_name = process.env.VUE_APP_REPO_NAME;

router.use((req, res, next) => {
    console.log(`路由执行成功啦~~~`, Date.now());
    next()
})

const urls = {
    'tags': () => `/repos/${repo_name}/labels`,
    'list': () => `/repos/${repo_name}/issues`,
    'query': () => `/search/issues`,
    'article': (id) => `/repos/${repo_name}/issues/${id}`,
}

const buildUrl = (baseUrl, params) => {
    let url = baseUrl;
    let paramsArray = [];
    //拼接参数
    Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
    if (url.search(/\?/) === -1) {
        url += '?' + paramsArray.join('&')
    } else {
        url += '&' + paramsArray.join('&')
    }
    return url;
}

router.get(`/issues`, (req, res, next) => {
    const { action, id, ...rest } = req.query;

    const baseUrl = urls[action](id);

    const params = Object.assign({ access_token, repo: repo_name }, rest);

    let url = buildUrl(baseUrl, params)
    console.log(url);

    fetch(`${GITEE_API}${url}`).then(response => {
        if (!response.ok) {
            console.log(response)
            throw new Error('Network response was not OK');
        }
        return response.json();
    }).then(data => {
        res.json({
            status: 200,
            data,
        })
    }).catch(error => {
        console.error('There has been a problem with your fetch operation:', error);
    });

})

router.get(`/loadimage`, (req, res, next) => {
    const { path } = req.query;

    const url = `https://images.gitee.com/uploads/images/${path}`;

    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not OK');
            }
            return response.arrayBuffer();
        })
        .then(buffer => {
            res.write(new Uint8Array(buffer));
            res.status(200);
            res.end();
        })
        .catch(error => {
            console.error('There has been a problem with your fetch operation:', error);
        });
})

module.exports = router